package com.framework.log.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * ip工具类
 * 
 * @author zzg
 * @date 2024-12-28
 * @since 1.0
 */
@Component
public class IpUtils {
    private static final Logger log = LoggerFactory.getLogger(IpUtils.class);
    @Value("${ip-local:true}")
    private boolean ipLocal;
    private static final String UNKNOWN = "unknown";
    private Searcher searcher = null;

    @PostConstruct
    public void init() {
        if (ipLocal) {
            String path = "ip2region/ip2region.xdb";
            ClassPathResource resource = new ClassPathResource(path);
            if (!resource.exists()) {
                log.error("找不到资源文件:{}", path);
                return;
            }
            try (InputStream inputStream = resource.getInputStream()) {
                byte[] cBuff = IoUtil.readBytes(inputStream);
                searcher = Searcher.newWithBuffer(cBuff);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 获取ip地址
     */
    public String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String comma = ",";
        String localhost = "127.0.0.1";
        if (ip.contains(comma)) {
            ip = ip.split(",")[0];
        }
        if (localhost.equals(ip)) {
            // 获取本机真正的ip地址
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                log.error(e.getMessage(), e);
            }
        }
        return ip;
    }

    /**
     * 根据ip获取详细地址
     */
    public String getCityInfo(String ip) {
        if (ipLocal) {
            return getLocalCityInfo(ip);
        } else {
            return getHttpCityInfo(ip);
        }
    }

    /**
     * 根据ip获取详细地址
     */
    public String getHttpCityInfo(String ip) {
        String api = String.format(LogConstant.Url.IP_URL, ip);
        JSONObject object = JSONUtil.parseObj(HttpUtil.get(api));
        return object.get("addr", String.class);
    }

    /**
     * 根据ip获取详细地址
     */
    public String getLocalCityInfo(String ip) {
        if (ObjectUtils.isEmpty(searcher)) {
            return StringUtils.EMPTY;
        }
        try {
            return searcher.search(ip);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return StringUtils.EMPTY;
    }
}
